package com.weigongbao.weigongbao;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;

public class GsonRequest<T> extends Request<T> {

    private Response.Listener<T> listener;
    private Class clase;

    public GsonRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
    }

    public GsonRequest(String url, Class clase, Response.ErrorListener error, Response.Listener<T> listener) {
        this(Request.Method.GET, url, error);
        this.listener = listener;
        this.clase = clase;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        String data;
        try {
            data = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            //Gson解析
        } catch (UnsupportedEncodingException e) {
            data = new String(response.data);
        }
        return (Response<T>) Response.success(new Gson().fromJson(data, clase), HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);//成功的回调
    }
}
